﻿var SPListQuickFilter = {
    headerFormat: '<h2 class="ms-standardheader">{Header}</h2><ul style="margin:0; padding: 0.5em 0 0.5em 1.5em; line-height: 1.5em;">',
    baseHref: null,
    cacheKey: null,
    cachedViews: null,
    cachedFilters: null,
    cachedChoices: null,
    filterField: null,
    filterValue: null,

    showSidebar: function () {
        var listViewTd = $("#MSOZoneCell_WebPartWPQ2");
        if (listViewTd.length != 1) return;

        if (SPListQuickFilter.Resources[_spPageContextInfo.currentLanguage]) {
            SPListQuickFilter.res = SPListQuickFilter.Resources[_spPageContextInfo.currentLanguage];
        } else {
            SPListQuickFilter.res = SPListQuickFilter.Resources[SPListQuickFilter.DefaultLanguage];
        }
        var res = SPListQuickFilter.res;

        var searchPos = location.href.indexOf("?");
        SPListQuickFilter.baseHref = (searchPos >= 0) ? location.href.substr(0, searchPos) : location.href;

        var html = '<td id="sp-list-sidebar" valign="top" nowrap="nowrap" style="width: 150px; border-right: 0px solid #dbddde; background: #f3f3f3; padding: 8px;">' +
            SPListQuickFilter.headerFormat.replace('{Header}', res.General) +
            '<li><a href="' + SPListQuickFilter.baseHref + '">(' + res.ClearFilter + ')</a></li>' +
            '<li><a id="sp-list-sidebar-created-by-you">' + res.CreatedByYou + '</a></li>' +
            '<li><a id="sp-list-sidebar-modified-by-you">' + res.ModifiedByYou + '</a></li>' +
            '</ul><div id="sp-list-sidebar-dynamic">';

        SPListQuickFilter.cacheKey = "SPListQuickFilter." + _spPageContextInfo.pageListId.toLowerCase() + ".";

        // Views
        SPListQuickFilter.cachedViews = sessionStorage.getItem(SPListQuickFilter.cacheKey + "Views");
        if (SPListQuickFilter.cachedViews && SPListQuickFilter.cachedViews.length) {
            var views = SPListQuickFilter.cachedViews.split("\n");
            if (views.length > 0 && views.length % 2 == 0) {
                html += SPListQuickFilter.createViews(views);
            }
        }

        SPListQuickFilter.filterField = GetUrlKeyValue("FilterField1", false);
        SPListQuickFilter.filterValue = GetUrlKeyValue("FilterValue1", false);

        // Filters
        SPListQuickFilter.cachedFilters = sessionStorage.getItem(SPListQuickFilter.cacheKey + "Filters");
        if (SPListQuickFilter.cachedFilters && SPListQuickFilter.cachedFilters.length) {
            var filters = SPListQuickFilter.cachedFilters.split("\n");
            if (filters.length > 0 && filters.length % 2 == 0) {
                SPListQuickFilter.cachedChoices = new Array();
                var choicesList = new Array();
                for (var i = 0; i < filters.length; i += 2) {
                    var internalName = filters[i];
                    var choicesText = sessionStorage.getItem(SPListQuickFilter.cacheKey + internalName);
                    SPListQuickFilter.cachedChoices.push(choicesText);
                    if (choicesText) {
                        choicesList.push(choicesText.split("\n"));
                    } else {
                        choicesList.push(new Array());
                    }
                }
                html += SPListQuickFilter.createFilters(filters, choicesList);
            }
        }

        html += '</div></td>';
        listViewTd.before(html);
    },

    showSidebarDelay: function () {
        var sidebar = $("td#sp-list-sidebar");
        var dynamic = sidebar.find("#sp-list-sidebar-dynamic");
        if (sidebar.length != 1 && dynamic.length != 1) return;

        var context = SP.ClientContext.get_current();
        var web = context.get_web();
        var user = web.get_currentUser();
        var listId = new SP.Guid(_spPageContextInfo.pageListId);
        var list = web.get_lists().getById(listId);
        var fields = list.get_fields();
        var views = list.get_views();
        context.load(user);
        context.load(fields);
        context.load(views);
        context.executeQueryAsync(function () {
            // General
            var userName = user.get_title();
            /// Created by You
            var addtionalParam = 'FilterField1=Author&FilterValue1=' + encodeURIComponent(userName);
            var createdByYou = sidebar.find("a#sp-list-sidebar-created-by-you");
            if (location.href.indexOf(addtionalParam) > 0) {
                createdByYou.css("font-weight", "bold");
            } else {
                createdByYou.attr("href", SPListQuickFilter.baseHref + '?' + addtionalParam);
            }
            /// Modified by You
            addtionalParam = 'FilterField1=Editor&FilterValue1=' + encodeURIComponent(userName);
            var modifiedByYou = sidebar.find("a#sp-list-sidebar-modified-by-you");
            if (location.href.indexOf(addtionalParam) > 0) {
                modifiedByYou.css("font-weight", "bold");
            } else {
                modifiedByYou.attr("href", SPListQuickFilter.baseHref + '?' + addtionalParam);
            }

            var cacheExpired = false;

            // View
            var viewsCache = null;
            var viewsArray = new Array();
            if (views.get_count() > 1) {
                var viewEnumerator = views.getEnumerator();
                while (viewEnumerator.moveNext()) {
                    var view = viewEnumerator.get_current();
                    var title = view.get_title();
                    if (!title) continue;
                    var url = view.get_serverRelativeUrl();
                    viewsArray.push(url);
                    viewsArray.push(title);
                }
                if (viewsArray.length / 2 > 1) {
                    viewsCache = viewsArray.join("\n");
                }
            }
            if (viewsCache != SPListQuickFilter.cachedViews) {
                cacheExpired = true;
            }

            // Filters
            var filtersCache = null;
            var filtersArray = new Array();
            var choicesCache = new Array();
            var choicesList = new Array();
            var filterIndex = 0;
            var fieldEnumerator = fields.getEnumerator();
            while (fieldEnumerator.moveNext()) {
                var field = fieldEnumerator.get_current();
                if (field.get_fieldTypeKind() != SP.FieldType.choice) continue;

                var internalName = field.get_internalName();
                var displayName = field.get_title();
                filtersArray.push(internalName);
                filtersArray.push(displayName);

                var choiceField = context.castTo(field, SP.FieldChoice);
                var choices = choiceField.get_choices();
                if (!$.isArray(choices)) choices = new Array();
                var choicesText = choices.join("\n");
                choicesList.push(choices);
                choicesCache.push(choicesText);

                if (!cacheExpired) {
                    if (!$.isArray(SPListQuickFilter.cachedChoices) || SPListQuickFilter.cachedChoices.length <= filterIndex || choicesText != SPListQuickFilter.cachedChoices[filterIndex]) {
                        cacheExpired = true;
                    }
                }

                filterIndex++;
            }
            if (filtersArray.length > 0) {
                filtersCache = filtersArray.join("\n");
            }
            if (!cacheExpired && filtersCache != SPListQuickFilter.cachedFilters) {
                cacheExpired = true;
            }

            if (!cacheExpired) return;

            var html = '<div id="sp-list-sidebar-dynamic">';
            if (viewsArray.length / 2 > 1) {
                html += SPListQuickFilter.createViews(viewsArray);
            }
            html += SPListQuickFilter.createFilters(filtersArray, choicesList) + '</div>';
            dynamic.replaceWith(html);

            // save cache
            if (viewsCache) {
                sessionStorage.setItem(SPListQuickFilter.cacheKey + "Views", viewsCache);
            } else {
                sessionStorage.removeItem(SPListQuickFilter.cacheKey + "Views");
            }
            if (filtersCache) {
                sessionStorage.setItem(SPListQuickFilter.cacheKey + "Filters", filtersCache);
                for (var i = 0; i < filtersArray.length; i += 2) {
                    var internalName = filtersArray[i];
                    sessionStorage.setItem(SPListQuickFilter.cacheKey + internalName, choicesCache[i / 2]);
                }
            } else {
                sessionStorage.removeItem(SPListQuickFilter.cacheKey + "Filters");
            }
        }, function () { });
    },

    createViews: function (views) {
        var html = SPListQuickFilter.headerFormat.replace('{Header}', SPListQuickFilter.res.Views);
        for (var i = 0; i < views.length; i += 2) {
            html += SPListQuickFilter.createView(views[i], views[i + 1]);
        }
        html += '</ul>';
        return html;
    },

    createView: function (url, title) {
        var encodedUrl = encodeURI(url);
        if (encodedUrl.toLowerCase() == location.pathname.toLowerCase()) {
            return '<li><b>' + SPListQuickFilter.htmlEscape(title) + '</b></li>';
        } else {
            return '<li><a href="' + encodedUrl + '">' + SPListQuickFilter.htmlEscape(title) + '</a></li>';
        }
    },

    createFilters: function (filters, choicesList) {
        var html = "";
        for (var i = 0; i < filters.length; i += 2) {
            var internalName = filters[i];
            var displayName = filters[i + 1];
            var choices = choicesList[i / 2];
            if (choices.length) {
                html += SPListQuickFilter.createFilter(internalName, displayName, choices);
            }
        }
        return html;
    },

    createFilter: function (internalName, displayName, choices) {
        var isCurrentFilter = (SPListQuickFilter.filterField == internalName);
        var filterHref = SPListQuickFilter.baseHref + '?FilterField1=' + encodeURIComponent(internalName) + '&FilterValue1=';
        var html = SPListQuickFilter.headerFormat.replace('{Header}', SPListQuickFilter.htmlEscape(displayName));
        if (isCurrentFilter && !SPListQuickFilter.filterValue) {
            html += '<li><b>(' + SPListQuickFilter.res.Empty + ')</b></li>';
        } else {
            html += '<li><a href="' + filterHref + '">(' + SPListQuickFilter.res.Empty + ')</a></li>';
        }
        for (var i = 0; i < choices.length; i++) {
            var choice = choices[i];
            if (isCurrentFilter && SPListQuickFilter.filterValue == choice) {
                html += '<li><b>' + SPListQuickFilter.htmlEscape(choice) + '</b></li>';
            } else {
                html += '<li><a href="' + filterHref + encodeURIComponent(choice) + '">' + SPListQuickFilter.htmlEscape(choice) + '</a></li>';
            }
        }
        html += '</ul>';
        return html;
    },

    htmlEscape: function (text) {
        return text ? (text.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/'/g, "&#039;").replace(/</g, "&lt;").replace(/>/g, "&gt;")) : "";
    },

    addEvent: function (eventName, func) {
        if (window.attachEvent) {
            window.attachEvent("on" + eventName, func);
        } else if (window.addEventListener) {
            window.addEventListener(eventName, func, false);
        }
    }
};

var locHref = location.href;
if (locHref.indexOf("/_layouts/") < 0 && locHref.indexOf("/Lists/") > 0 && locHref.indexOf("/DispForm.aspx") < 0 && locHref.indexOf("/NewForm.aspx") < 0 && locHref.indexOf("/EditForm.axpx") < 0) {
    if (!(window.jQuery)) {
        document.write('<script type="text/javascript" src="../SPListQuickFilterFiles/jquery-1.4.4.min.js"></' + 'script>');
    }
    document.write('<script type="text/javascript" src="../SPListQuickFilterFiles/Resources.js"></' + 'script>');
    SPListQuickFilter.addEvent("load", function () {
        if (!window.ctx || !ctx.view) return;
        SPListQuickFilter.showSidebar();
        ExecuteOrDelayUntilScriptLoaded(function () {
            SPListQuickFilter.showSidebarDelay();
        }, "sp.js");
    });
}
